<?php

/**

 * 支付回调

 *

 *

 *

 *

 * @copyright  Copyright (c) 2007-2015 ShopNC Inc. (http://www.shopnc.net)

 * @license    http://www.shopnc.net

 * @link       http://www.shopnc.net

 * @since      File available since Release v1.1

 */

defined('ByShopWWI') or exit('Access Invalid!');

class paymentControl extends mobileHomeControl {

	private $payment_code;

	public function __construct() {

		parent::__construct();

		$this -> payment_code = $_GET['payment_code'];

	}

	/**

	 * 支付回调

	 */

	public function returnOp() {

		unset($_GET['act']);

		unset($_GET['op']);

		unset($_GET['payment_code']);

		$payment_api = $this -> _get_payment_api();

		$payment_config = $this -> _get_payment_config();

		$callback_info = $payment_api -> getReturnInfo($payment_config);
		if ($callback_info) {

			//验证成功

			$result = $this -> _update_order($callback_info['out_trade_no'], $callback_info['trade_no']);

			if ($result['state']) {

				Tpl::output('result', 'success');

				Tpl::output('message', '支付成功');

			} else {

				Tpl::output('result', 'fail');

				Tpl::output('message', '支付失败');

			}

		} else {

			//验证失败

			Tpl::output('result', 'fail');

			Tpl::output('message', '支付失败');

		}

		Tpl::showpage('payment_message');

	}

	/**

	 * 支付提醒

	 */

	public function notifyOp() {

		// wxpay_jsapi

		if ($this -> payment_code == 'wxpay_jsapi') {

			$api = $this -> _get_payment_api();

			$params = $this -> _get_payment_config();

			$api -> setConfigs($params);

			list($result, $output) = $api -> notify();

			if ($result) {

				$internalSn = $result['out_trade_no'] . '_' . $result['attach'];

				$externalSn = $result['transaction_id'];

				$updateSuccess = $this -> _update_order($internalSn, $externalSn);

				if (!$updateSuccess) {

					// @todo

					// 直接退出 等待下次通知

					exit ;

				}

			}

			echo $output;

			exit ;

		}

		// 恢复框架编码的post值

		$_POST['notify_data'] = html_entity_decode($_POST['notify_data']);

		$payment_api = $this -> _get_payment_api();

		$payment_config = $this -> _get_payment_config();

		$callback_info = $payment_api -> getNotifyInfo($payment_config);

		if ($callback_info) {

			//验证成功

			$result = $this -> _update_order($callback_info['out_trade_no'], $callback_info['trade_no']);

			if ($result['state']) {

				echo 'success';
				die ;

			}

		}

		//验证失败

		echo "fail";
		die ;

	}

	/**

	 * 获取支付接口实例

	 */

	private function _get_payment_api() {

		$inc_file = BASE_PATH . DS . 'api' . DS . 'payment' . DS . $this -> payment_code . DS . $this -> payment_code . '.php';

		if (is_file($inc_file)) {

			require ($inc_file);

		}

		$payment_api = new $this->payment_code();

		return $payment_api;

	}

	/**

	 * 获取支付接口信息

	 */

	private function _get_payment_config() {

		$model_mb_payment = Model('mb_payment');

		//读取接口配置信息

		$condition = array();

		if ($this -> payment_code == 'wxpay3') {

			$condition['payment_code'] = 'wxpay';

		} else {

			$condition['payment_code'] = $this -> payment_code;

		}

		$payment_info = $model_mb_payment -> getMbPaymentOpenInfo($condition);

		return $payment_info['payment_config'];

	}

	/**

	 * 更新订单状态

	 */

	private function _update_order($out_trade_no, $trade_no) {

		$model_order = Model('order');

		$logic_payment = Logic('payment');

		$tmp = explode('_', $out_trade_no);

		$out_trade_no = $tmp[0];

		if (!empty($tmp[1])) {

			$order_type = $tmp[1];

		} else {

			$order_pay_info = Model('order') -> getOrderPayInfo(array('pay_sn' => $out_trade_no));

			if (empty($order_pay_info)) {

				$order_type = 'v';

			} else {

				$order_type = 'r';

			}

		}
		//exit(print($order_type));

		// wxpay_jsapi

		$paymentCode = $this -> payment_code;

		if ($paymentCode == 'wxpay_jsapi') {

			$paymentCode = 'wx_jsapi';

		} elseif ($paymentCode == 'wxpay3') {

			$paymentCode = 'wxpay';

		}

		if ($order_type == 'r') {

			$result = $logic_payment -> getRealOrderInfo($out_trade_no);

			if (intval($result['data']['api_pay_state'])) {

				return array('state' => true);

			}

			$order_list = $result['data']['order_list'];

			$result = $logic_payment -> updateRealOrder($out_trade_no, $paymentCode, $order_list, $trade_no);

			$api_pay_amount = 0;

			if (!empty($order_list)) {

				foreach ($order_list as $order_info) {

					$api_pay_amount += $order_info['order_amount'] - $order_info['pd_amount'] - $order_info['rcb_amount'];

				}

			}

			$log_buyer_id = $order_list[0]['buyer_id'];

			$log_buyer_name = $order_list[0]['buyer_name'];

			$log_desc = '实物订单使用' . orderPaymentName($paymentCode) . '成功支付，支付单号：' . $out_trade_no;

		} elseif ($order_type == 'v') {

			$result = $logic_payment -> getVrOrderInfo($out_trade_no);

			$order_info = $result['data'];

			if (!in_array($result['data']['order_state'], array(ORDER_STATE_NEW, ORDER_STATE_CANCEL))) {

				return array('state' => true);

			}

			$result = $logic_payment -> updateVrOrder($out_trade_no, $paymentCode, $result['data'], $trade_no);

			$api_pay_amount = $order_info['order_amount'] - $order_info['pd_amount'] - $order_info['rcb_amount'];

			$log_buyer_id = $order_info['buyer_id'];

			$log_buyer_name = $order_info['buyer_name'];

			$log_desc = '虚拟订单使用' . orderPaymentName($paymentCode) . '成功支付，支付单号：' . $out_trade_no;

		} elseif ($order_type == 'upgradepdrecharge') {
			$model_pd = Model('predeposit');
			$recharge_info = $model_pd -> getPdRechargeInfo(array('pdr_sn' => $out_trade_no));
			$condition = array();
			$condition['pdr_sn'] = $out_trade_no;
			$condition['pdr_payment_state'] = 0;
			$update = array();
			$update['pdr_payment_state'] = 1;
			$update['pdr_payment_time'] = TIMESTAMP;
			$update['pdr_payment_code'] = $paymentCode;
			$update['pdr_payment_name'] = orderPaymentName($paymentCode);
			$update['pdr_trade_sn'] = $trade_no;
			$pamount = $recharge_info['pdr_amount'];
			if ($recharge_info['pdr_payment_state']) {
				$result = array();
				$result['state'] = 0;
				return $result;
				//已支付过
			}

			$upjifen = $pamount;
			$baijifen = $pamount * 100;

			//增加积分经验值

			Model() -> execute('update shopwwi_member set member_exppoints = member_exppoints + "' . $upjifen . '" where member_id=' . $recharge_info['pdr_member_id']);

			//增加白积分

			Model() -> execute('update shopwwi_member set member_points = member_points + ' . $baijifen . ' where member_id=' . $recharge_info['pdr_member_id']);

			$back_points = $pamount * 100;

			$pl_addtime = strtotime(date("Y-m-d"));

			$member_id = $recharge_info['pdr_member_id'];

			$sql_bc = "insert into shopwwi_points_log (pl_memberid,pl_membername,pl_points,pl_addtime,pl_desc,pl_stage) values($member_id,'$membername',$back_points,$pl_addtime,'VIP升级积分','upgradepoints')";

			Model() -> execute($sql_bc);

			$model_member = Model('member');

			//$member_grade = $model_member->where(array('member_id'=>$recharge_info['pdr_member_id']))->getMemberGradeArr();

			$member_list = $model_member -> where(array('member_id' => $recharge_info['pdr_member_id'])) -> Select();

			//经验值

			$invite_one = $member_list[0]['invite_one'];

			$invite_two = $member_list[0]['invite_two'];

			$invite_three = $member_list[0]['invite_three'];

			$member_name = $member_list[0]['member_name'];

			$vip = $member_list[0]['member_exppoints'];
			// 当前会员经验值
			$model_member = Model('member');
			if ($invite_one > 0) {

				$member_oneinfo = $model_member -> getMemberInfo(array('member_id' => $invite_one));
				$member_onegradeinfo = $model_member -> getOneMemberGrade(intval($member_oneinfo['member_exppoints']));

				$yuer = $invite_one + $vip_one + 0.5;

				//Model()->execute('update shopwwi_member set available_predeposit = available_predeposit + '.$yuer.'  where member_id=33');

				//$vip_one_one=$md_one_list[0]['invite_one'];//一级分佣

				//$vip_one_two=$md_one_list[0]['invite_two'];//二级分佣

				//Model()->execute('update shopwwi_member set available_predeposit = available_predeposit + '.$yuer.'  where member_id=33');

				//  Model()->execute('update shopwwi_member set available_predeposit = available_predeposit + 0.03  where member_id=33');

				//***************一级分佣

				//if($vip_one_one > 0){

				$fy_one = $pamount * $member_onegradeinfo['shengjifx'];

				//查询上级会员

				$m_name = $member_oneinfo['member_name'];

				$m_id = $member_oneinfo['member_id'];

				$fy_jifen = $baijifen * $member_onegradeinfo['shengjifx'];

				$fy_cash = $pamount * $member_onegradeinfo['shengjifx'];

				//现金

				Model() -> execute('update shopwwi_member set available_predeposit = available_predeposit + ' . $fy_cash . ' where member_id=' . $m_id);

				//积分

				Model() -> execute('update shopwwi_member set member_points = member_points + ' . $fy_jifen . ' where member_id=' . $m_id);

				//积分日志

				$sql_bc = "insert into shopwwi_points_log (pl_memberid,pl_membername,pl_points,pl_addtime,pl_desc,pl_stage) values($m_id,'$m_name',$fy_one,$pl_addtime,'" . $member_name . "的返佣积分','backpoints')";

				Model() -> execute($sql_bc);

				//}

				//***************
			}

			//*******************************************

			if ($invite_two > 0) {

				$member_oneinfo = $model_member -> getMemberInfo(array('member_id' => $invite_two));
				$member_onegradeinfo = $model_member -> getOneMemberGrade(intval($member_oneinfo['member_exppoints']));

				//Model()->execute('update shopwwi_member set available_predeposit = available_predeposit + '.$yuer.'  where member_id=33');

				//$vip_one_one=$md_one_list[0]['invite_one'];//一级分佣

				//$vip_one_two=$md_one_list[0]['invite_two'];//二级分佣

				//Model()->execute('update shopwwi_member set available_predeposit = available_predeposit + '.$yuer.'  where member_id=33');

				//  Model()->execute('update shopwwi_member set available_predeposit = available_predeposit + 0.03  where member_id=33');

				//***************一级分佣

				//if($vip_one_one > 0){

				$fy_one = $pamount * $member_onegradeinfo['nshengjifx'];

				//查询上级会员

				$m_name = $member_oneinfo['member_name'];

				$m_id = $member_oneinfo['member_id'];

				$fy_jifen = $baijifen * $member_onegradeinfo['nshengjifx'];

				$fy_cash = $pamount * $member_onegradeinfo['nshengjifx'];

				//现金

				Model() -> execute('update shopwwi_member set available_predeposit = available_predeposit + ' . $fy_cash . ' where member_id=' . $m_id);

				//积分

				Model() -> execute('update shopwwi_member set member_points = member_points + ' . $fy_jifen . ' where member_id=' . $m_id);

				//积分日志

				$sql_bc = "insert into shopwwi_points_log (pl_memberid,pl_membername,pl_points,pl_addtime,pl_desc,pl_stage) values($m_id,'$m_name',$fy_one,$pl_addtime,'" . $member_name . "的返佣积分','backpoints')";

				Model() -> execute($sql_bc);

			}
			if ($invite_three > 0) {

				$member_oneinfo = $model_member -> getMemberInfo(array('member_id' => $invite_three));
				$member_onegradeinfo = $model_member -> getOneMemberGrade(intval($member_oneinfo['member_exppoints']));

				//Model()->execute('update shopwwi_member set available_predeposit = available_predeposit + '.$yuer.'  where member_id=33');

				//$vip_one_one=$md_one_list[0]['invite_one'];//一级分佣

				//$vip_one_two=$md_one_list[0]['invite_two'];//二级分佣

				//Model()->execute('update shopwwi_member set available_predeposit = available_predeposit + '.$yuer.'  where member_id=33');

				//  Model()->execute('update shopwwi_member set available_predeposit = available_predeposit + 0.03  where member_id=33');

				//***************一级分佣

				//if($vip_one_one > 0){

				$fy_one = $pamount * $member_onegradeinfo['nsale_tc'];

				//查询上级会员

				$m_name = $member_oneinfo['member_name'];

				$m_id = $member_oneinfo['member_id'];

				$fy_jifen = $baijifen * $member_onegradeinfo['nsale_tc'];

				$fy_cash = $pamount * $member_onegradeinfo['nsale_tc'];

				//现金

				Model() -> execute('update shopwwi_member set available_predeposit = available_predeposit + ' . $fy_cash . ' where member_id=' . $m_id);

				//积分

				Model() -> execute('update shopwwi_member set member_points = member_points + ' . $fy_jifen . ' where member_id=' . $m_id);

				//积分日志

				$sql_bc = "insert into shopwwi_points_log (pl_memberid,pl_membername,pl_points,pl_addtime,pl_desc,pl_stage) values($m_id,'$m_name',$fy_one,$pl_addtime,'" . $member_name . "的返佣积分','backpoints')";

				Model() -> execute($sql_bc);

			}
			//********************************************

			//$pl_addtime=strtotime(date("Y-m-d"));

			//$sql_bc="insert into shopwwi_points_log(pl_memberid,pl_membername,pl_points,pl_addtime,pl_desc,pl_stage) values(1,'puhui',$vip,$pl_addtime,'返佣积分','backpoints')";

			//Model()->execute($sql_bc);

			//自身充值升级积分

			//预存款可用余额

			$model_pd = Model('predeposit');
			$state = $model_pd -> editPdRecharge($update, $condition);
			if (!$state) {

				$result = array();
				$result['state'] = 0;
				return $result;

			} else {
				$result = array();
				$result['state'] = 1;
				return $result;
			}

		} elseif ($order_type == 'kucunpdrecharge') {
			$model_pd = Model('predeposit');
			$recharge_info = $model_pd -> getPdRechargeInfo(array('pdr_sn' => $out_trade_no));
			$condition = array();
			$condition['pdr_sn'] = $out_trade_no;
			$condition['pdr_payment_state'] = 0;
			$update = array();
			$update['pdr_payment_state'] = 1;
			$update['pdr_payment_time'] = TIMESTAMP;
			$update['pdr_payment_code'] = $paymentCode;
			$update['pdr_payment_name'] = orderPaymentName($paymentCode);
			$update['pdr_trade_sn'] = $trade_no;
			$pamount = $recharge_info['pdr_amount'];
			if ($recharge_info['pdr_payment_state']) {
				$result = array();
				$result['state'] = 0;
				return $result;
				//已支付过
			}
			//kucunpdrecharge
			$kcjf = $pamount * 625;
			Model() -> execute('update shopwwi_member set kucun_points = kucun_points + ' . $kcjf . ' where member_id=' . $recharge_info['pdr_member_id']);
			//积分日志
			$m_id = $recharge_info['pdr_member_id'];
			$pl_addtime = strtotime(date("Y-m-d"));
			$model_member = Model('member');
			//$member_grade = $model_member->where(array('member_id'=>$recharge_info['pdr_member_id']))->getMemberGradeArr();
			$member_list = $model_member -> where(array('member_id' => $recharge_info['pdr_member_id'])) -> Select();
			$member_name = $member_list[0]['member_name'];
			$sql_bc = "insert into shopwwi_points_log(pl_memberid,pl_membername,pl_points,pl_addtime,pl_desc,pl_stage) values($m_id,'$member_name',$kcjf,$pl_addtime,'库存积分','kucunpoints')";
			Model() -> execute($sql_bc);
			/**/
			$model_pd = Model('predeposit');
			$state = $model_pd -> editPdRecharge($update, $condition);
			if (!$state) {

				$result = array();
				$result['state'] = 0;
				return $result;

			} else {
				$result = array();
				$result['state'] = 1;
				return $result;
			}

		} elseif ($order_type == 'pdrecharge') {
			$condition = array();
			$condition['pdr_sn'] = $out_trade_no;
			$condition['pdr_payment_state'] = 0;
			$update = array();
			$update['pdr_payment_state'] = 1;
			$update['pdr_payment_time'] = TIMESTAMP;
			$update['pdr_payment_code'] = $paymentCode;
			$update['pdr_payment_name'] = orderPaymentName($paymentCode);
			$update['pdr_trade_sn'] = $trade_no;
			$model_pd = Model('predeposit');
			$recharge_info = $model_pd -> getPdRechargeInfo(array('pdr_sn' => $out_trade_no));
			if ($recharge_info['pdr_payment_state']) {
				$result = array();
				$result['state'] = 0;
				return $result;
				//已支付过
			}
			$state = $model_pd -> editPdRecharge($update, $condition);
			if ($state) {
				$data = array();
				$data['member_id'] = $recharge_info['pdr_member_id'];
				$data['member_name'] = $recharge_info['pdr_member_name'];
				$data['amount'] = $recharge_info['pdr_amount'];
				$data['pdr_sn'] = $recharge_info['pdr_sn'];
				$model_pd -> changePd('recharge', $data);
				$result = array();
				$result['state'] = 1;
				return $result;
			} else {
				$result = array();
				$result['state'] = 0;
				return $result;
			}

		}

		if ($result['state']) {

			//记录消费日志

			QueueClient::push('addConsume', array('member_id' => $log_buyer_id, 'member_name' => $log_buyer_name, 'consume_amount' => ncPriceFormat($api_pay_amount), 'consume_time' => TIMESTAMP, 'consume_remark' => $log_desc));

		}

		return $result;

	}

}
